package com.yaowk.weixin.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.yaowk.weixin.model.Config;

/**
 * Created by yaowk on 17-8-1.
 */
public class ApiInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        Controller controller = invocation.getController();
        if (!(controller instanceof ApiController)) {
            throw new RuntimeException("控制器需要继承 ApiController");
        } else {
            try {
                Integer platformId = controller.getParaToInt("platformId");
                Config config = Config.dao.findFirst(Kv.by("platform_id = ", platformId));
                ApiConfigKit.setThreadLocalAppId(config.getAppId());
                invocation.invoke();
            } finally {
                ApiConfigKit.removeThreadLocalAppId();
            }

        }
    }
}
